import React, { Component } from 'react';
import {
  View,
  StyleSheet,
  Text,
  FlatList,
  TextInput,
  Keyboard,
  TouchableNativeFeedback,
  DeviceEventEmitter,
} from 'react-native';
import Icon from 'react-native-vector-icons/AntDesign';
import {
  BlankBackground,
  ListFooter,
} from '../../components';
import TaskItem from '../main/inspection/task-item';
import {
  PollingItem,
} from '../../components/polling';
import * as inspectionService from '../../services/inspection';
import ZlstIcon from '../../components/zlst-icons';
import Theme from '../../native-base-theme/variables/commonColor';
import { commonMethods } from '../../utils';
import * as request from '../../services/pollingRequest';

const fontColor = '#ffffff';
class RecordSearch extends Component {
  currentPage = 1

  rows = 5

  initListhener = null

  constructor(props) {
    super(props);
    this.state = {
      listData: [],
      refreshing: false,
      isError: false,
      isMore: false,
      searchValue: '',
    };
  }

  componentDidMount() {
    this.initListhener = DeviceEventEmitter.addListener('swipeToInpectionSearch', this._swipeToThisPage);
  }

  _swipeToThisPage = () => {
    this.state.listData = [];
    this.currentPage = 1;
    this._onSearch();
  }

  /**
   * 刷新数据，如果flag为true，那么不拼接数据到现有数据列表之后
  */
  _onSearch = async (flag = false, searchType) => {
    try {
      // DeviceEventEmitter.emit('showLoading', true);
      const { searchValue } = this.state;
      // const qeury = {
      //   equipmentCode: '',
      //   condition: searchValue,
      //   page: this.currentPage,
      //   pageSize: this.rows,
      // };
      // const resp = await request.checkRecord(qeury);

      const { list, page, total } = await inspectionService.queryCheckTask({
        page: this.currentPage,
        isMyTask: false,
        condition: searchValue,
      });
      // this.setState({ listData: list });
      // DeviceEventEmitter.emit('showLoading', false);
      if (list && list.length) {
        this.setState(preState => {
          let newList;
          if (flag) {
            newList = list;
          } else {
            newList = preState.listData.concat(list);
          }
          let isMore;
          if (newList.length >= total) {
            isMore = false;
          } else {
            isMore = true;
          }
          return ({
            listData: newList,
            isMore,
          });
        });
      } else if (searchType === 'search') {
        this.setState({
          listData: [],
        });
      } else {
        this.setState({
          isMore: false,
        });
      }
      // console.log('polling resp:', resp);
    } catch (error) {
      // DeviceEventEmitter.emit('showLoading', false);
      console.log('点巡检记录查询报错');
    }
  }

  _clearInput = () => {
    this.setState({
      searchValue: '',
    });
  }

  _toMianPage = () => {
    console.log('to main page!');
    DeviceEventEmitter.emit('swiperIncidentPageEvent', 1);
  }

  _itemClick = (data) => {
    console.log('search page item click:', data);
    global.navigation.navigate({
      routeName: 'TaskDeviceDetail',
      params: {
        equipcheckId: data.item.equipcheckId,
        equipmentCode: data.item.equipmentCode,
        equipmentName: data.item.equipmentName,
      },
    });
  }

  /**
   * 行渲染方法
  */
  renderRow = (item) => <TaskItem item={item.item} onItemClick={this._onItemClick} />

  // 刷新
  _onRefresh = () => {
    console.log('refresh!');
    this.currentPage = 1;
    this._onSearch(true);
  }

  // 上拉加载数据
  _onEndReached = () => {
    console.log('endReached!');
    if (this.state.isMore) {
      this.currentPage += 1;
      this._onSearch();
    }
  }

  // 列表上拉加载没有数据时
  _renderListFooter = () => (
    (this.state.listData.length > 0) && <ListFooter isMore={this.state.isMore} />
  )

  // 获取数据
  _queryData = async () => {
  }

  _getListContent = () => {
    const { listData, refreshing, isError } = this.state;
    if (listData && !listData.length) {
      return (
        <BlankBackground isError={isError} onRefresh={this._onRefresh} />
      );
    }
    return (
      <FlatList
        showsVerticalScrollIndicator={false}
        data={listData}
        renderItem={item => this.renderRow(item)}
        keyExtractor={(item, index) => item + index}
        onRefresh={this._onRefresh}
        refreshing={refreshing}
        onEndReachedThreshold={0.3}
        scrollEventThrottle={200}
        onEndReached={this._onEndReached}
        ListFooterComponent={this._renderListFooter}
      />
    );
  }

  _onSubmitEditing = () => {
    Keyboard.dismiss();
    this.currentPage = 1;
    this._onSearch(true, 'search');
  }

  _dismissKeyboard = () => {
    Keyboard.dismiss();
  }

  render() {
    return (
      <View style={{ width: '100%', height: '100%' }}>
        <View style={styles.pageContainer}>
          <View style={[styles.headerContent, styles.padding8]}>
            <ZlstIcon
              onPress={this._toMianPage}
              name="fanhui"
              size={24}
              color="white"
            />
            <Text style={{ color: fontColor, fontSize: 18, fontWeight: 'bold' }}>巡检记录查询</Text>
            <View style={styles.titleOtherInfo} />
          </View>
          <View style={[styles.searchContent, styles.padding8]}>
            <ZlstIcon
              style={[styles.searchIcon, { left: 15 }]}
              name="sousuokuangnei"
              size={22}
              color="white"
            />
            <View style={styles.searchAndBtn}>
              <TextInput
                value={this.state.searchValue}
                style={styles.textInput}
                underlineColorAndroid="transparent"
                placeholder="设备名称/巡检人"
                placeholderTextColor="#ffffff"
                onChangeText={searchValue => this.setState({ searchValue })}
                onSubmitEditing={this._onSubmitEditing}
              />
              <TouchableNativeFeedback onPress={this._onSubmitEditing}>
                <View style={styles.searchBtn}>
                  <Text style={styles.searchBtnText}>搜 索</Text>
                </View>
              </TouchableNativeFeedback>
            </View>
            {!commonMethods.isEmpty(this.state.searchValue) && (
              <Icon
                style={[styles.searchIcon, { right: 77 }]}
                name="closecircle"
                size={22}
                color="#a4a4a4"
                onPress={this._clearInput}
              />)}
          </View>
          <View style={styles.listContent}>
            {this._getListContent()}
          </View>
        </View>
      </View>
    );
  }
}

const seatchHeight = 48;

const styles = StyleSheet.create({
  pageContainer: {
    backgroundColor: Theme.myPrimary,
    width: '100%',
    flex: 1,
  },
  padding8: {
    paddingLeft: 8,
    paddingRight: 8,
  },
  headerContent: {
    display: 'flex',
    flexDirection: 'row',
    height: 40,
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: Theme.myPrimary,
    marginBottom: 8,
  },
  titleOtherInfo: {
    width: 24,
    height: 24,
  },
  searchContent: {
    backgroundColor: Theme.myPrimary,
    position: 'relative',
    height: seatchHeight,
  },
  searchAndBtn: {
    display: 'flex',
    flex: 1,
    flexDirection: 'row',
  },
  searchBtn: {
    width: 60,
    backgroundColor: 'rgba(255, 255, 255, 0.15)',
    borderLeftWidth: 1,
    borderStyle: 'solid',
    borderLeftColor: '#ffffff',
    borderTopRightRadius: 5,
    borderBottomRightRadius: 5,
  },
  searchBtnText: {
    color: '#ffffff',
    lineHeight: seatchHeight,
    textAlign: 'center',
    fontWeight: 'bold',
  },
  searchIcon: {
    position: 'absolute',
    top: 14,
  },
  textInput: {
    flex: 1,
    fontSize: 16,
    color: '#ffffff',
    backgroundColor: 'rgba(255, 255, 255, 0.15)',
    paddingLeft: 38,
    paddingRight: 38,
    borderTopLeftRadius: 5,
    borderBottomLeftRadius: 5,
  },
  listContent: {
    flex: 1,
    marginTop: 4,
  },
});

export default RecordSearch;
